package com.zlq.cn;

import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;

import java.io.File;

/**
 * @author zhoucl
 * @date 2021/2/7 12:36
 */
public class BaidubcePictrans {
    private static final String BD_APPID = "23645388";
    private static final String BD_APIKEY = "Im7FduA2KCaWlkC7hBZC0qRr";
    private static final String BD_SECKEY = "yPSZykmBinXNyZ34ll3KL9qsCI2WLYbI";
    private static final String GET_TOKEN = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s";
    private static final String BAIDUBCE_PICTRANS = "https://aip.baidubce.com/file/2.0/mt/pictrans/v1?access_token=%s";
    private static final String ACCESS_TOKEN = "24.04963a409c47ea0f67bdee7b306309c1.2592000.1615264907.282335-23645388";
    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(getHttpLoggingInterceptor())
            .build();

    public static void main(String[] args) throws Exception {
        //getAuth();
        MultipartBody.Builder builder = new MultipartBody.Builder();
        File file = new File("C:\\Users\\asus\\Desktop\\test.jpg");
        builder.addFormDataPart("image", file.getName(), RequestBody.create(file, MediaType.get("multipart/form-data")));
        builder.addFormDataPart("from", "zh");
        builder.addFormDataPart("to", "en");
        builder.setType(MediaType.get("multipart/form-data"));
        Request request = new Request.Builder()
                .url(String.format(BAIDUBCE_PICTRANS, ACCESS_TOKEN))
                .header("Content-Type", "mutipart/form-data")
                .post(builder.build())
                .build();
        String string = okHttpClient.newCall(request).execute().body().string();
        System.out.println(string);
    }

    private static String getAuth() throws Exception {
        Request request = new Request.Builder()
                .url(String.format(GET_TOKEN, BD_APIKEY, BD_SECKEY))
                .get()
                .build();
        String string = okHttpClient.newCall(request).execute().body().string();
        System.out.println(string);
        return string;
        //https://aip.baidubce.com/oauth/2.0/token
    }

    private static HttpLoggingInterceptor getHttpLoggingInterceptor() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.level(HttpLoggingInterceptor.Level.BODY);
        return httpLoggingInterceptor;
    }
}
